package com.zx.flow.security;

import com.zx.flow.api.util.AssertUtil;
import com.zx.flow.api.util.JWTUtil;
import com.zx.flow.core.cache.SecretCache;
import com.zx.flow.db.entity.FlowSecretEntity;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        String jwt = request.getHeader(JWTUtil.JWT_KEY);
        String secretId = request.getHeader(JWTUtil.SECRETID_KEY);
        AssertUtil.checkSecurity(jwt, "token校验失败, token为空");
        AssertUtil.checkSecurity(secretId, "token校验失败, secretId为空");

        FlowSecretEntity secretKey = SecretCache.get(secretId);
        AssertUtil.checkSecurity(secretKey, "token校验失败, secretId非法");

        String accountCode = JWTUtil.verifyAndGet(secretId, secretKey.getSecretKey(), jwt, String.class);
        AssertUtil.checkSecurity(accountCode, "token校验失败, 用户信息为空");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


}
